package com.lawyer.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.lawyer.dynamic.Criteria;
import com.lawyer.dynamic.Restrictions;
import com.lawyer.entity.Config;
import com.lawyer.entity.Lawyer;
import com.lawyer.entity.LawyerCaseInfo;
import com.lawyer.entity.LawyerMicroScoreInfo;
import com.lawyer.entity.User;
import com.lawyer.entity.Withdrawal;
import com.lawyer.model.CertificationRequest;
import com.lawyer.model.Message;
import com.lawyer.model.MessageConstant;
import com.lawyer.model.UpudateLawyerReq;
import com.lawyer.repository.ConfigRepository;
import com.lawyer.repository.LawyerCaseInfoRepository;
import com.lawyer.repository.LawyerMicroScoreInfoRepository;
import com.lawyer.repository.LawyerRepository;
import com.lawyer.repository.MoneyFlowsRepository;
import com.lawyer.repository.SystemUserRepository;
import com.lawyer.repository.UserRepository;
import com.lawyer.repository.WithdrawalRepository;
import com.lawyer.service.LawyerService;
import com.lawyer.uitls.BeanUtils;

@RestController
@RequestMapping(value = "/system")
@Api(tags = "系统管理-律师")
@SuppressWarnings("all")
public class SystemLawyerController {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private SystemUserRepository systemUserRepository;

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private LawyerRepository lawyerRepository;

	@Autowired
	private MoneyFlowsRepository moneyFlowsRepository;
	@Autowired
	private EntityManager entityManager;

	@Autowired
	private WithdrawalRepository withdrawalRepository;
	
	
	@Autowired
	private LawyerService lawyerService;
	
	@Autowired
	private LawyerCaseInfoRepository lawyerCaseInfoRepository;
	
	@Autowired
	private LawyerMicroScoreInfoRepository lawyerMicroScoreInfoRepository;
	
	@Autowired
	private ConfigRepository configRepository;
	
	
	

	@ApiOperation(httpMethod = "GET", value = "查询所有律师列表", notes = "查询所有律师列表")
	@RequestMapping(value = "/lawyers", method = RequestMethod.GET)
	@ApiImplicitParams({ @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query", value = "第几页"),
			@ApiImplicitParam(name = "size", dataType = "integer", paramType = "query", value = "分页条数") })
	public HttpEntity<?> lawyers(String nickName, String phone, @PageableDefault(page = 0, direction = Sort.Direction.DESC) Pageable pageable) {
		Message msg = new Message();
		try {
			Criteria<Lawyer> criteria = new Criteria<Lawyer>();

			if (StringUtils.isNotEmpty(nickName)) {
				criteria.add(Restrictions.like("nickName", "%" + nickName + "%", true));
			}

			if (StringUtils.isNotEmpty(phone)) {
				criteria.add(Restrictions.like("phone", phone, true));
			}

			Page<Lawyer> page = lawyerRepository.findAll(criteria, pageable);
			msg.setData(page);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "GET", value = "查看律师详情", notes = "查看律师详情")
	@RequestMapping(value = "/info", method = RequestMethod.GET)
	public HttpEntity<?> info(String lawyerId) {
		Message msg = new Message();

		Lawyer lawyer = lawyerRepository.findOne(lawyerId);
		lawyer.setPassword(null);

		try {
			if (lawyer != null) {
				// 经典案例
				List<LawyerCaseInfo> list = lawyerCaseInfoRepository.findTop4ByLawyerIdOrderByStarLevelDesc(lawyerId);
				lawyer.setLawyerCaseInfos(list);
				// 连麦评分
				List<LawyerMicroScoreInfo> maiScoreLogs = lawyerMicroScoreInfoRepository.findTop4ByLawyerIdOrderByScoreDesc(lawyerId);
				lawyer.setMaiScoreLogs(maiScoreLogs);
				for (LawyerMicroScoreInfo scoreInfo : maiScoreLogs) {

					User user = userRepository.findOne(scoreInfo.getUserId());
					if (user != null) {
						scoreInfo.setNickName(user.getNickName());
						scoreInfo.setHeaderIco(user.getHeaderIco());
					}
				}
				Config config = configRepository.findByName("ConsultingFee");// 律师咨询费
				lawyer.setConsultPrice(Double.valueOf(config.getValue()));
				
				Config configPhone = configRepository.findByName("LawyerShowPhone");// 律师电话
				lawyer.setPhone(configPhone.getValue());

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		msg.setData(lawyer);

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}
	

	@ApiOperation(httpMethod = "GET", value = "入住申请列表", notes = "律师是否认证,0=未认证,1=审核中,2=审核通过,3=审核不通过")
	@RequestMapping(value = "/applyList", method = RequestMethod.GET)
	public HttpEntity<?> applyList() {
		Message msg = new Message();
		try {
			CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
			CriteriaQuery<Lawyer> criteriaQuery = criteriaBuilder.createQuery(Lawyer.class);
			Root<Lawyer> root = criteriaQuery.from(Lawyer.class);

			// 查询条件or 或者
			List<Predicate> predicates = new ArrayList<>();
			Predicate pred1 = criteriaBuilder.equal(root.get("certification"), 1);
			Predicate pred2 = criteriaBuilder.equal(root.get("certification"), 3);
			predicates.add(criteriaBuilder.or(pred1, pred2));

			// 将所有条件用 and 联合起来
			if (!CollectionUtils.isEmpty(predicates)) {
				criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
			}

			// 记录当前sql查询结果总条数
			List<Lawyer> counts = entityManager.createQuery(criteriaQuery).getResultList();
			TypedQuery<Lawyer> createQuery = entityManager.createQuery(criteriaQuery);

			msg.setData(createQuery.getResultList());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "GET", value = "认证(通过/驳回)", notes = "certification : 2=通过,3=驳回")
	@RequestMapping(value = "/certification", method = RequestMethod.GET)
	public HttpEntity<?> certification(String lawyerId, Integer certification) {
		Message msg = new Message();

		Lawyer lawyer = lawyerRepository.findOne(lawyerId);
		if (lawyer != null) {

			if (StringUtils.isEmpty(lawyer.getLicensedUrl())) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("请上传证件号");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}

			lawyer.setCertification(certification);
			lawyerRepository.save(lawyer);
		} else {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage("没有找到该律师.");
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "POST", value = "添加律师(后台添加律师默认为已认证的律师)", notes = "添加律师")
	@RequestMapping(value = "/lawyerRegister", method = RequestMethod.POST)
	public HttpEntity<?> lawyerRegister(@RequestBody CertificationRequest certificationRequest) {
		Message msg = new Message();

		if (StringUtils.isEmpty(certificationRequest.getLicensedUrl())) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage("请上传证件号");
			return new ResponseEntity<>(msg, HttpStatus.OK);
		}

		Lawyer lawyer = lawyerRepository.findOne(certificationRequest.getLawyerId());
		if (lawyer != null) {
			BeanUtils.copyPropertiesIgnoreNullValue(certificationRequest, lawyer,"starLevel","certification","workYear","doorPermissions","recommend");
			lawyer.setCertification(2);
			lawyerRepository.save(lawyer);
		} else {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage("没有找到该律师.");
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "GET", value = "更新提现状态", notes = "stauts：1=提现中,2=提现完成,3=提现失败")
	@RequestMapping(value = "/withdrawalUpdate", method = RequestMethod.GET)
	public HttpEntity<?> withdrawalUpdate(Long id, Integer stauts) {
		Message msg = new Message();
		try {
			Withdrawal withdrawal = withdrawalRepository.findOne(id);
			if (withdrawal != null) {
				withdrawal.setStauts(stauts);
				withdrawalRepository.save(withdrawal);
			} else {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("没有找到提现订单");
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}
	
	@ApiOperation(httpMethod = "POST", value = "律师基本修改，主页，擅长分类，认证", notes = "律师基本修改，主页，擅长分类，认证")
	@RequestMapping(value = "/updateLawyerInfo", method = RequestMethod.POST)
	public HttpEntity<?> updateLawyerInfo(@RequestBody UpudateLawyerReq lawyerReq) {
		Message msg = new Message();
		
		Lawyer findLawyer = lawyerRepository.findOne(lawyerReq.getLawyerId());
		if (findLawyer != null) {
			BeanUtils.copyPropertiesIgnoreNullValue(lawyerReq, findLawyer,"starLevel","certification","workYear","doorPermissions","recommend");
			lawyerRepository.save(findLawyer);
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}
	
}
